package com.hbfec.intergration.yqdata;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * java代码将链接转换为二维码
 * @Description： TODO
 * @author ：
 * @date ：2021年7月6日 下午2:58:05
 */
public class EweimaFile1 {

		public static void main(String[] args) {
		    String url = "https://mp.weixin.qq.com/s/zR-P85p4QEN4Ho3oXPQsMw";
		    String base664pic = createQrCode(url);
		    int xx=0;
		}

	/***
	 * url转base64二维码主方法
	 * @param url
	 * @return
	 */
		public static String createQrCode(String url) {
		    try {
			    Map<EncodeHintType, String> hints = new HashMap<>();
			    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			    BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 400, 400, hints);
			    return writeToBase64(bitMatrix, "jpg");
		    } catch (Exception e) {
			    e.printStackTrace();
		    }
		    return null;
		}

	/***
	 * bit矩阵变量转base64码
	 * @param matrix
	 * @return
	 */
		static String writeToBase64(BitMatrix matrix, String format) throws IOException {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流

		    BufferedImage image = toBufferedImage(matrix);
		    if (!ImageIO.write(image, format, baos)) {
			    throw new IOException("Could not write an image of format " + format + " to " );
			}

			byte[] bytes = baos.toByteArray();//转换成字节
			BASE64Encoder encoder = new BASE64Encoder();
			String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
			System.out.println(png_base64);
			png_base64 = "data:image/jpg;base64," + png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
			System.out.println("值为：" + png_base64);
			return png_base64;
		}

		private static final int BLACK = 0xFF000000;
	    private static final int WHITE = 0xFFFFFFFF;

		private static BufferedImage toBufferedImage(BitMatrix matrix) {
		    int width = matrix.getWidth();
		    int height = matrix.getHeight();
		    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		    for (int x = 0; x < width; x++) {
			    for (int y = 0; y < height; y++) {
				    image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
				}
			}
		    return image;
		}
}

